#!/usr/bin/env bash

# Filename     :	aswcron-server-install.sh
# Last modified:	2023-10-22 11:12
# Version      :
# Author       : jack.zang
# Email        : jack.zang@aishangwei.net
# Description  :
# 使用方法：source <(curl -sL https://gitee.com/jack_zang/public-scripts/raw/master/shell/aswcron/aswcron-server-install.sh)
# ******************************************************

## 请先手工创建 /etc/aswcron/config.yaml
if [ ! -f "/etc/aswcron/config.yaml" ];then
  echo "请先手工创建配置文件：/etc/aswcron/config.yaml"
  exit
fi

useradd aswcron
mkdir /var/log/aswcron -pv

read -t 30 -p "请输入要安装的 aswcron-server 版本，例：v1.0.0 ,直接回车安装默认版本 v1.0.0：" ASWCRON_SERVER

[ -z "$ASWCRON_SERVER" ] && ASWCRON_SERVER="v1.0.0"

curl -Lo /tmp/aswcron-server-${ASWCRON_SERVER}-linux-amd64.tar.gz \
     https://file.aishangwei.net/aswcron/aswcron-server-${ASWCRON_SERVER}-linux-amd64.tar.gz

# kill 已经运行的 aswcron-node
cronPid=`ps -ef | grep aswcron-server | grep -v grep | grep -v nohup | tr -s ' ' | cut -d ' ' -f 2`
if (( $cronPid )); then
  kill -9 $cronPid
fi
##ps -ef | grep aswcron-node | grep -v grep | grep -v nohup | tr -s ' ' | cut -d ' ' -f 2 | xargs kill -9

rm -f /usr/local/bin/aswcron-server*
tar xf  /tmp/aswcron-server-${ASWCRON_SERVER}-linux-amd64.tar.gz -C /usr/local/bin/
ln -s /usr/local/bin/aswcron-server-${ASWCRON_SERVER} /usr/local/bin/aswcron-server
chmod +x /usr/local/bin/aswcron-server-${ASWCRON_SERVER}

chown aswcron /usr/local/bin/aswcron-server* && chown -R aswcron /var/log/aswcron
chown aswcron /etc/aswcron/config.yaml
sudo -u aswcron nohup /usr/local/bin/aswcron-server -c /etc/aswcron/config.yaml >> /var/log/aswcron/server.log 2>&1 &

chmod +x /etc/rc.d/rc.local
sed  -i "/aswcron-server/d" /etc/rc.d/rc.local
echo "sudo -u aswcron nohup /usr/local/bin/aswcron-server -c /etc/aswcron/config.yaml >> /var/log/aswcron/server.log 2>&1 &" >> /etc/rc.d/rc.local

















